package com.imageim.yimirror.ui.activity;

import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import com.imageim.yimirror.R;
import com.imageim.yimirror.base.BaseActivity;
import com.imageim.yimirror.base.BaseFragment;

/**
 * Created by Bruce.Zhou on 2018/11/22 10:17.
 * Email: 907160968@qq.com
 */
public abstract class BaseFragmentActivity extends BaseActivity {
    protected BaseFragment currentFragment;
    protected FragmentManager mFragmentManager;

    public void showFragmentView(BaseFragment fragment, String tag) {
        if (mFragmentManager == null) {
            mFragmentManager = getSupportFragmentManager();
        }
        FragmentTransaction mFragmentTransaction = mFragmentManager.beginTransaction();
        //优先检查，fragment是否存在，避免重叠
        BaseFragment tempFragment = (BaseFragment) mFragmentManager.findFragmentByTag(tag);
        if (tempFragment != null) {
            fragment = tempFragment;
        }
        if (fragment.isAdded()) {
            addOrShowFragment(fragment, tag);
        } else {
            if (currentFragment != null && currentFragment.isAdded()) {
                mFragmentTransaction.hide(currentFragment).add(R.id.fl_container, fragment, tag).commitAllowingStateLoss();
            } else {
                mFragmentTransaction.add(R.id.fl_container, fragment, tag).commitAllowingStateLoss();
            }
            currentFragment = fragment;
        }
    }


    /**
     * 添加或者显示 fragment
     *
     * @param fragment
     */
    private void addOrShowFragment(BaseFragment fragment, String tag) {
        if (currentFragment == null || currentFragment == fragment || mFragmentManager == null) {
            return;
        }
        // 如果当前fragment未被添加，则添加到Fragment管理器中
        FragmentTransaction transaction = mFragmentManager.beginTransaction();
        if (!fragment.isAdded()) {
            transaction.hide(currentFragment).add(R.id.fl_container, fragment, tag).commitAllowingStateLoss();
        } else {
            transaction.hide(currentFragment).show(fragment).commitAllowingStateLoss();
        }

        currentFragment.setUserVisibleHint(false);
        currentFragment = fragment;
        currentFragment.setUserVisibleHint(true);
    }

}
